import sheinConfig from "./platform/shein";
import temuConfig from "./platform/temu";
import { chunkArray, sendMessage } from "./utils";
import CurrencyConverter from "./currencyConverter";

const converter = new CurrencyConverter();

let getCurrentPage = () => {
  return 1;
};
let getPageSize = () => {
  return 10;
};
let getTotalPageSize = () => {
  return 10;
};
let getRequestHeaders = () => {
  return {
    "Content-Type": "application/json",
  };
};
let getErpSkuMathField = () => {
  return "outId";
};
let formatSourcePrice = (price: any) => {
  return price;
};
// 定义 getProductBySkuMap 的类型
interface GetProductBySkuMapParams {
  pageNum: number;
  pageSize: number;
  skuCodeList: any[];
  productBySkuAndCostPriceMap: any;
  productBySkuCurrencyMap: any;
}

type GetProductBySkuMapFn = (params: GetProductBySkuMapParams) => Promise<any>;

let getProductBySkuMap: GetProductBySkuMapFn = async () => ({});

// 定义 formatSaveParams 的类型
interface FormatSaveParamsInput {
  productBySkuMap: any;
  skuPurchasePriceMap: any;
  multiplier: number;
}

type FormatSaveParamsFn = (params: FormatSaveParamsInput) => any;

let formatSaveParams: FormatSaveParamsFn = () => ({
  params: null,
  successTotal: 0,
  failTotal: 0,
});
let getDoAgreeToNegotiateUrl = () => {
  return "";
};

function setConfigByPlatform(platform: string) {
  if (platform === "shein") {
    ({
      getCurrentPage,
      getPageSize,
      getTotalPageSize,
      getProductBySkuMap,
      formatSaveParams,
      getDoAgreeToNegotiateUrl,
    } = sheinConfig);
  } else if (platform === "temu") {
    ({
      getCurrentPage,
      getPageSize,
      getTotalPageSize,
      getProductBySkuMap,
      formatSaveParams,
      getDoAgreeToNegotiateUrl,
      getRequestHeaders,
      getErpSkuMathField,
      formatSourcePrice,
    } = temuConfig);
  }
}

// 在全局添加时间控制配置
interface TimingConfig {
  baseDelay: number; // 基础延迟时间
  randomRange: number; // 随机延迟范围
  fatigueThreshold: number; // 疲劳操作阈值
}

const timing: TimingConfig = {
  baseDelay: 500, // 3秒基础延迟
  randomRange: 500, // 0-7秒随机延迟
  fatigueThreshold: 10, // 连续10次操作后触发疲劳模式
};

interface ApiResponse<T = any> {
  code: number;
  msg?: string;
  data?: T;
}

// Loading 遮罩管理器
const LoadingManager = {
  // 初始化遮罩元素
  init: function () {
    // 如果已经存在则不再创建
    if (document.getElementById("js-loading-overlay")) return;

    // 创建遮罩元素
    const overlay = document.createElement("div");
    overlay.id = "js-loading-overlay";

    // 创建内容容器
    const content = document.createElement("div");
    content.className = "js-loading-content";

    // 创建 spinner
    const spinner = document.createElement("div");
    spinner.className = "js-loading-spinner";

    // 创建文本元素
    const text = document.createElement("div");
    text.id = "js-loading-text";
    text.className = "js-loading-text";
    text.textContent = "加载中...";

    // 组装结构
    content.appendChild(spinner);
    content.appendChild(text);
    overlay.appendChild(content);
    document.body.appendChild(overlay);

    // 添加样式
    this.addStyles();
  },

  // 添加样式
  addStyles: function () {
    const style = document.createElement("style");
    style.textContent = `
      #js-loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        display: none;
        justify-content: center;
        align-items: center;
        z-index: 9999;
      }
      
      .js-loading-content {
        background-color: white;
        padding: 20px;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        align-items: center;
        min-width: 200px;
      }
      
      .js-loading-spinner {
        border: 4px solid rgba(0, 0, 0, 0.1);
        border-radius: 50%;
        border-top: 4px solid #3498db;
        width: 40px;
        height: 40px;
        animation: js-loading-spin 1s linear infinite;
        margin-bottom: 15px;
      }
      
      .js-loading-text {
        margin-top: 10px;
        font-size: 16px;
        color: #333;
      }
      
      @keyframes js-loading-spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
    `;
    document.head.appendChild(style);
  },

  // 显示 loading
  show: function (text = "加载中...") {
    this.init(); // 确保元素已初始化
    const overlay = document.getElementById("js-loading-overlay");
    const loadingText = document.getElementById("js-loading-text");
    if (loadingText) {
      loadingText.textContent = text;
    }
    if (overlay) {
      overlay.style.display = "flex";
    }
  },

  // 隐藏 loading
  hide: function () {
    const overlay = document.getElementById("js-loading-overlay");
    if (overlay) {
      overlay.style.display = "none";
    }
  },

  // 设置提示文字
  setText: function (text: string) {
    const loadingText = document.getElementById("js-loading-text");
    if (loadingText) {
      loadingText.textContent = text;
    }
  },
};

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (
    request.action === "automaticallyAgreeToNegotiateAction" ||
    request.action === "automaticallyAgreeToNegotiateActionByCostPrice"
  ) {
    checkLoginAndStartScraping(request.action);
  }
});

// 智能延迟函数
function intelligentDelay(pageCount: number): Promise<void> {
  return new Promise((resolve) => {
    // 疲劳模式检测
    const fatigueMultiplier = pageCount > timing.fatigueThreshold ? 1.5 : 1;
    // 计算最终延迟时间
    const delay =
      timing.baseDelay * fatigueMultiplier + Math.random() * timing.randomRange;

    setTimeout(resolve, delay);
  });
}

// 异步执行函数
async function executeSequentially(asyncFunctions: any[]) {
  // 遍历异步函数数组，使用索引判断位置
  for (let index = 0; index < asyncFunctions.length; index++) {
    const asyncFunc = asyncFunctions[index];
    try {
      // 执行当前异步函数
      await asyncFunc();

      // 检查是否为最后一个函数（通过索引判断）
      // 如果不是最后一个，添加随机延迟
      if (index !== asyncFunctions.length - 1) {
        // 生成0.5-1秒之间的随机延迟时间(毫秒)
        const delayMs = 500 + Math.random() * 500;
        await new Promise((resolve) => setTimeout(resolve, delayMs));
      }
    } catch (error) {
      // 如果有函数执行失败，返回reject
      return Promise.reject(error);
    }
  }

  // 所有函数都执行成功
  return Promise.resolve();
}

// sku平台建议价格
let productBySkuMap: any = {};
let skuCodeList: any = [];
// sku原始建议价格
let productBySkuAndCostPriceMap: any = {};
let productBySkuCurrencyMap: any = {};

function clearData() {
  productBySkuMap = {};
  skuCodeList = [];
  productBySkuAndCostPriceMap = {};
  productBySkuCurrencyMap = {};
}

// 开始后禁用按钮
function startAutoMaticallyAgreeToNegotiateChangeBtn(actionType: string) {
  LoadingManager.show("正在自动同意建议价，请稍候...");
}

function endAutoMaticallyAgreeToNegotiateChangeBtn(actionType: string) {
  LoadingManager.hide();
}

async function doAutomaticallyAgreeToNegotiate({
  skuPurchasePriceMap,
  multiplier,
  action,
  platform,
}: {
  multiplier: number;
  skuPurchasePriceMap: any;
  action: string;
  platform: string;
}) {
  const {
    paramsList,
    successTotal,
    failTotal,
    skipCount = 0,
    updateBatchBysSkuNoGenerateParams,
  } = formatSaveParams({
    productBySkuMap,
    skuPurchasePriceMap,
    multiplier,
  });

  if (paramsList?.length > 0) {
    const doAgreeToNegotiateUrl = getDoAgreeToNegotiateUrl();
    LoadingManager.setText(`正在执行操作,请稍等...`);
    const fetchArray = paramsList.map((params: any) => {
      const headers = getRequestHeaders();
      return () => {
        return fetch(doAgreeToNegotiateUrl, {
          method: "POST",
          headers,
          body: JSON.stringify(params),
        });
      };
    });
    executeSequentially(fetchArray)
      .then(async () => {
        if (platform === "temu") {
          const storage = await chrome.storage.sync.get([
            "baoyiplus_accessToken",
          ]);
          const { baoyiplus_accessToken = "" } = storage;
          sendMessage<ApiResponse>({
            type: "updateBatchBysSkuNoGenerate",
            data: updateBatchBysSkuNoGenerateParams,
            platform,
            token: baoyiplus_accessToken,
          });
        }

        endAutoMaticallyAgreeToNegotiateChangeBtn(action);
        if (skipCount) {
          alert(
            `插件自动同意建议价成功，共同意${successTotal}个商品,拒绝${failTotal}个商品,请刷新页面.${skipCount}个商品没有采购价格,请确保所选店铺正确或者转成申报价格核价`
          );
        } else {
          alert(
            `插件自动同意建议价成功，共同意${successTotal}个商品,拒绝${failTotal}个商品,请刷新页面`
          );
        }
      })
      .catch((error) => {
        alert(error);
        endAutoMaticallyAgreeToNegotiateChangeBtn(action);
      });
  } else {
    endAutoMaticallyAgreeToNegotiateChangeBtn(action);
    if (skipCount) {
      alert(
        `没有符合规则的商品,已跳过${skipCount}个商品,请确保所选店铺正确或者转成申报价格核价`
      );
    } else {
      alert("插件自动同意建议价失败,没有符合规则的商品");
    }
  }
}

async function startCheckAndAgreeToNegotiate({
  multiplier,
  action,
  platform,
}: {
  multiplier: number;
  action: string;
  platform: string;
}) {
  const storage = await chrome.storage.sync.get([
    "baoyiplus_accessToken",
    "baoyiplus_expiresIn",
    "baoyiplus_username",
    "baoyiplus_shopId",
  ]);
  const { baoyiplus_accessToken = "", baoyiplus_shopId } = storage;
  if (action === "automaticallyAgreeToNegotiateActionByCostPrice") {
    doAutomaticallyAgreeToNegotiate({
      skuPurchasePriceMap: productBySkuAndCostPriceMap,
      multiplier,
      action,
      platform,
    });
    return;
  }
  const chunkSkuCodeList = chunkArray(skuCodeList, 50);

  const erpSkuMathField = getErpSkuMathField();
  const promiseArray: any[] = [];
  chunkSkuCodeList.forEach((skuCodeChunk) => {
    promiseArray.push(
      sendMessage<ApiResponse>({
        type: "callApi",
        data: {
          [erpSkuMathField]: `#in#${skuCodeChunk.join(",")}`,
          shopId: baoyiplus_shopId,
        },
        platform,
        token: baoyiplus_accessToken,
      })
    );
  });
  return Promise.all(promiseArray)
    .then(async (resList) => {
      const skuPurchasePriceMap: any = {};
      for (const res of resList) {
        const dataList = res?.data || [];
        for (const record of dataList) {
          const { [erpSkuMathField]: id, sourcePrice, sourceCurrency } = record;
          if (id && sourceCurrency) {
            try {
              const convertPrice = await converter.convert(
                sourcePrice,
                sourceCurrency,
                productBySkuCurrencyMap[id]
              );
              skuPurchasePriceMap[id] = formatSourcePrice(convertPrice);
            } catch (error) {
              console.log(error);
            }
          }
        }
      }
      doAutomaticallyAgreeToNegotiate({
        skuPurchasePriceMap,
        multiplier,
        action,
        platform,
      });
    })
    .catch(() => {
      endAutoMaticallyAgreeToNegotiateChangeBtn(action);
    });
}

async function autoScrape({
  basePage = 1,
  pageSize = 10,
  pageCount = 0,
  maxPages = 5,
  multiplier = 1,
  action,
  platform,
}: {
  basePage: number;
  pageSize: number;
  pageCount: number;
  maxPages: number;
  multiplier: number;
  action: string;
  platform: string;
}): Promise<void> {
  if (pageCount < maxPages) {
    try {
      // 前置延迟
      await intelligentDelay(pageCount);
      LoadingManager.setText(
        `正在收集商品信息(${pageCount + 1}/${maxPages})，请稍候...`
      );
      const formatSkuMap = await getProductBySkuMap({
        pageNum: basePage + pageCount,
        pageSize,
        skuCodeList,
        productBySkuAndCostPriceMap,
        productBySkuCurrencyMap,
      });
      productBySkuMap = {
        ...productBySkuMap,
        ...formatSkuMap,
      };
      autoScrape({
        pageCount: pageCount + 1,
        maxPages,
        multiplier,
        basePage,
        pageSize,
        action,
        platform,
      });
    } catch (error) {
      autoScrape({
        pageCount: pageCount + 1,
        maxPages,
        multiplier,
        basePage,
        pageSize,
        action,
        platform,
      });
      console.error("异常:", error);
    }
  } else {
    startCheckAndAgreeToNegotiate({ multiplier, action, platform });
  }
}

// 检查token是否过期（针对时间戳格式）
function checkTokenExpired(expiresIn: string | number): boolean {
  if (!expiresIn) return true;

  // 统一转换为数字
  const expiryTime =
    typeof expiresIn === "string" ? parseInt(expiresIn) : expiresIn;

  // 获取当前时间戳（毫秒）
  const currentTime = new Date().getTime();
  return currentTime > expiryTime;
}

function getInputValues(action: string): Promise<{
  maxPages: number;
  numberMultiplier: number;
  platform: string;
} | null> {
  // 创建对话框容器
  const dialog = document.createElement("div");
  dialog.style.position = "fixed";
  dialog.style.top = "50%";
  dialog.style.left = "50%";
  dialog.style.transform = "translate(-50%, -50%)";
  dialog.style.backgroundColor = "white";
  dialog.style.padding = "20px";
  dialog.style.borderRadius = "8px";
  dialog.style.boxShadow = "0 0 10px rgba(0,0,0,0.2)";
  dialog.style.zIndex = "9999";
  const multiplierText =
    action === "automaticallyAgreeToNegotiateActionByCostPrice"
      ? `<label style="display: block; margin-bottom: 5px;">报价记录倍率：(平台建议价 >=  报价记录 * 倍率)</label>`
      : `<label style="display: block; margin-bottom: 5px;">采购价倍率：(平台建议价 >=  采购价 * 倍率)</label>`;

  const defaultPlatform =
    location.href.includes("seller.kuajingmaihuo") ||
    location.href.includes("temu")
      ? "temu"
      : "shein";
  // 创建HTML内容
  dialog.innerHTML = `
    <h3 style="margin-top: 0;">操作起始页从当前页开始</h3>
    <div style="margin-bottom: 15px;">
      <label style="display: block; margin-bottom: 5px;">平台：</label>
      <select id="platformSelect" style="width: 100%; padding: 8px; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px;">
        <option value="shein">SHEIN</option>
        <option value="temu">Temu</option>
      </select>
    </div>
    <div style="margin-bottom: 15px;">
      <label style="display: block; margin-bottom: 5px;">自动同意建议价的页数：</label>
      <input type="number" id="maxPagesInput" value="5" 
             style="width: 100%; padding: 8px; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px;">
    </div>
    <div style="margin-bottom: 15px;">
      ${multiplierText}
      <input type="number" id="multiplierInput" step="0.01" min="0.01" value="0.7" 
             style="width: 100%; padding: 8px; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px;">
    </div>
    <div style="display: flex; justify-content: space-between;">
      <button id="cancelBtn" style="padding: 8px 16px; background-color: #f44336; color: white; border: none; border-radius: 4px; cursor: pointer;">取消</button>
      <button id="confirmBtn" style="padding: 8px 16px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer;">确认</button>
    </div>
  `;

  // 添加到body
  document.body.appendChild(dialog);

  const maxPagesInput = document.getElementById(
    "maxPagesInput"
  ) as HTMLInputElement;
  const multiplierInput = document.getElementById(
    "multiplierInput"
  ) as HTMLInputElement;
  const platformSelect = document.getElementById(
    "platformSelect"
  ) as HTMLSelectElement;

  platformSelect.value = defaultPlatform;

  // 返回Promise
  return new Promise((resolve, reject) => {
    // 确认按钮点击事件
    document.getElementById("confirmBtn")?.addEventListener("click", () => {
      const maxPages = parseInt(maxPagesInput.value);
      const multiplier = parseFloat(multiplierInput.value);
      const platform = platformSelect.value;

      // 验证输入
      if (!platform) {
        alert("请选择平台！");
        reject();
        return;
      }

      // 验证输入
      if (isNaN(maxPages)) {
        alert("请输入有效的页数！");
        reject();
        return;
      }

      if (maxPages <= 0) {
        alert("页数必须大于0！");
        reject();
        return;
      }

      if (isNaN(multiplier)) {
        alert("请输入有效的倍率！");
        reject();
        return;
      }

      if (multiplier <= 0) {
        alert("倍率必须大于0！");
        reject();
        return;
      }

      // 移除对话框
      document.body.removeChild(dialog);

      // 返回结果
      resolve({ maxPages, numberMultiplier: multiplier, platform });
    });

    // 取消按钮点击事件
    document.getElementById("cancelBtn")?.addEventListener("click", () => {
      document.body.removeChild(dialog);
      resolve(null);
    });
  });
}

// Function to check login status and start scraping
async function checkLoginAndStartScraping(action: string) {
  const storage = await chrome.storage.sync.get([
    "baoyiplus_accessToken",
    "baoyiplus_expiresIn",
    "baoyiplus_username",
    "baoyiplus_shopId",
  ]);
  const {
    baoyiplus_accessToken = "",
    baoyiplus_expiresIn = 0,
    baoyiplus_shopId = "",
  } = storage;

  if (baoyiplus_accessToken) {
    const isExpired = checkTokenExpired(baoyiplus_expiresIn);
    if (!isExpired) {
      if (!baoyiplus_shopId) {
        alert("请先选择店铺！");
        return;
      }
      clearData();
      // 弹出输入框，提示用户输入采集页数
      getInputValues(action).then((data) => {
        if (data) {
          let { maxPages, numberMultiplier, platform } = data as any;
          setConfigByPlatform(platform);
          const basePage = getCurrentPage();
          const pageSize = getPageSize();
          const totalPage = getTotalPageSize();
          if (totalPage) {
            if (basePage - 1 + maxPages > totalPage) {
              maxPages = totalPage - basePage + 1;
            }
          }

          startAutoMaticallyAgreeToNegotiateChangeBtn(action);
          autoScrape({
            pageCount: 0,
            maxPages,
            multiplier: numberMultiplier,
            basePage,
            pageSize,
            action,
            platform,
          }); // 第三个参数为用户输入的页数
        }
      });
    } else {
      alert("登录已经过期，请先点击右上角重新登录");
    }
  } else {
    alert("还未登录，请先点击右上角插件进行登录");
  }
}
